package com.example.myapplication.frags;


import static android.app.Activity.RESULT_OK;
import static com.example.myapplication.utils.UserService.JSON;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;
import com.example.myapplication.data.GlobalData;
import com.example.myapplication.data.MessageEvent;
import com.example.myapplication.data.User;
import com.example.myapplication.module_user.LoginActivity;
import com.example.myapplication.module_user.MyQRCodeActivity;
import com.example.myapplication.utils.dommy.qrcode.util.Constant;
import com.example.myapplication.utils.google.zxing.activity.CaptureActivity;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserBasic_Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserBasic_Fragment extends Fragment {

    private static final int GET_CUR_USER = 3;
    private static final int UPDATE_USER = 4;
    AbsoluteLayout root;
    Handler handler;
    LayoutInflater layoutInflater;
    private String TAG = "UserBasic";
    public UserBasic_Fragment() {
        // Required empty public constructor
    }

    public static UserBasic_Fragment newInstance(String param1, String param2) {
        UserBasic_Fragment fragment = new UserBasic_Fragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onStart() {

        super.onStart();
        Log.d("Xx", "onHiddenChanged: 显示了！");
        if (GlobalData.isLogin) {
            Log.d(TAG, "JWT: " + GlobalData.jwt);
            root.removeAllViews();
            getLayoutInflater().inflate(R.layout.fragment_logined, (ViewGroup) root);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Gson gson = new Gson();
                    String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
                    Request request = new Request.Builder().
                            url("http://120.25.230.35:8080/user").addHeader("jwt", substring).get().build();
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response execute = call.execute();
                        if (execute.isSuccessful()) {
                            String stringUser = Objects.requireNonNull(execute.body()).string();
                            User user = gson.fromJson(stringUser, User.class);
                            Message message = new Message();
                            message.what = GET_CUR_USER;
                            message.obj = user;
                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            root.findViewById(R.id.btn_go_myQR).setOnClickListener(view->{
                Intent intent = new Intent(this.getContext(), MyQRCodeActivity.class);
                startActivity(intent);
            });
            //处理退出登录逻辑
            root.findViewById(R.id.btn_logout).setOnClickListener(view -> {
                GlobalData.isLogin = false;
                GlobalData.curUser = null;
                GlobalData.jwt = "";
                root.removeAllViews();
                getLayoutInflater().inflate(R.layout.fragment_user_basic, (ViewGroup) root);
                EventBus.getDefault().post(new MessageEvent(CommonService_Fragment.LOGOUT_EVENT));
                //重新注册事件。。真的蠢
                root.findViewById(R.id.btn_go_login).setOnClickListener(NONE_->{
                    Intent i = new Intent(this.getContext(), LoginActivity.class);
                    startActivity(i);
                });
            });
            Fragment fragment = this;
            root.findViewById(R.id.scan_btn).setOnClickListener(view -> {
               startQrCode();

            });
            root.findViewById(R.id.btn_edit).setOnClickListener(view -> {
                View inflate = getLayoutInflater().inflate(R.layout.edit_info, null);
                // 回显数据
                EditText et_class = inflate.findViewById(R.id.et_new_class);
                et_class.setText(GlobalData.curUser.getClassName());
                EditText et_role = inflate.findViewById(R.id.et_new_role);
                et_role.setText(GlobalData.curUser.getRole());
                EditText et_sex = inflate.findViewById(R.id.et_new_sex);
                et_sex.setText(GlobalData.curUser.getSex());
                EditText et_name = inflate.findViewById(R.id.et_new_name);
                et_name.setText(GlobalData.curUser.getName());
                EditText et_phone = inflate.findViewById(R.id.et_new_phone);
                et_phone.setText(GlobalData.curUser.getPhone());
                EditText et_email = inflate.findViewById(R.id.et_new_email);
                et_email.setText(GlobalData.curUser.getEmail());
                EditText et_school = inflate.findViewById(R.id.et_new_school);
                et_school.setText(GlobalData.curUser.getSchool());

                inflate.findViewById(R.id.btn_cfm_edit).setOnClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                User user = new User();
                                user.setClassName(et_class.getText().toString());
                                user.setName(et_name.getText().toString());
                                user.setPhone(et_phone.getText().toString());
                                user.setEmail(et_email.getText().toString());
                                user.setRole(et_role.getText().toString());
                                user.setSex(et_sex.getText().toString());
                                user.setSchool(et_school.getText().toString());
                                updateUser(user);
                            }
                        }
                );
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                builder.setView(inflate);
                builder.show();

            });
        }
    }

    private void updateUser(User user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Gson gson = new Gson();
                String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);

                RequestBody requestBody = RequestBody.create(JSON, gson.toJson(user));
                Request request = new Request.Builder().
                        url("http://120.25.230.35:8080/user").addHeader("jwt", substring).put(requestBody).build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response execute = call.execute();
                    if (execute.isSuccessful()) {
                        Message message = new Message();
                        message.what = UPDATE_USER;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    // 开始扫码
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                Toast.makeText(getActivity(), "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
            }
            // 申请权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(getContext(), CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            Gson gson = new Gson();
            User user = gson.fromJson(scanResult, User.class);
            Log.d(TAG, "onActivityResult: "+user);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(getActivity(), "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
        }
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case GET_CUR_USER:
                        User user = (User) msg.obj;
                        GlobalData.curUser = user;
                        TextView stuName = root.findViewById(R.id.tv_stuName);
                        stuName.setText(user.getName());
                        ImageView stuAvatar = root.findViewById(R.id.img_stuAvatar);
                        Glide.with(getContext()).load(user.getAvatar()).into(stuAvatar);
                        TextView stuId = root.findViewById(R.id.tv_stuId);
                        stuId.setText(user.getId().toString());
                        TextView stuSex = root.findViewById(R.id.tv_stuSex);
                        stuSex.setText(user.getSex());
                        TextView stuSchool = root.findViewById(R.id.tv_stuScho);
                        stuSchool.setText(user.getSchool());
                        TextView stuClass = root.findViewById(R.id.tv_stuClass);
                        stuClass.setText(user.getClassName());
                        TextView stuPhone = root.findViewById(R.id.tv_stuPhone);
                        stuPhone.setText(user.getPhone());
                        TextView stuEmail = root.findViewById(R.id.tv_stuEmail);
                        stuEmail.setText(user.getEmail());
                        TextView stuRole = root.findViewById(R.id.tv_stuRole);
                        stuRole.setText(user.getRole());

                        break;
                    case UPDATE_USER:
                        Toast.makeText(getContext(), "更新成功！", Toast.LENGTH_LONG).show();
                        // 取到最新的user
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                OkHttpClient okHttpClient = new OkHttpClient();
                                Gson gson = new Gson();
                                String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
                                Request request = new Request.Builder().
                                        url("http://120.25.230.35:8080/user").addHeader("jwt", substring).get().build();
                                Call call = okHttpClient.newCall(request);
                                try {
                                    Response execute = call.execute();
                                    if (execute.isSuccessful()) {
                                        String stringUser = Objects.requireNonNull(execute.body()).string();
                                        User user = gson.fromJson(stringUser, User.class);
                                        Message message = new Message();
                                        message.what = GET_CUR_USER;
                                        message.obj = user;
                                        handler.sendMessage(message);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                        break;
                }
            }
        };
        if (!GlobalData.isLogin) {
            Intent i = new Intent(this.getContext(), LoginActivity.class);
            startActivity(i);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("show", "onCreateView: show");
        // Inflate the layout for this fragment
        layoutInflater = inflater;
        root = (AbsoluteLayout) inflater.inflate(R.layout.fragment_user_basic, container, false);
        root.findViewById(R.id.btn_go_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!GlobalData.isLogin) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }
            }
        });


        return root;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Log.d("User_basic", "onMessageEvent: " + event);

    }

}